//
//  SinaHomeTableVC.swift
//  mySina
//
//  Created by 刘莹 on 2016/11/12.
//  Copyright © 2016年 liuying. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel

private let StatusCellId = "StatusCellId"
private let RetweetedCellId = "RetweetedCellId"
let navBarHeight: CGFloat = 64
class SinaHomeTableVC: SinaBaseTableVC {
    //MARK: -
    //MARK: - 懒加载控件
    //小菊花
    internal lazy var  indicatorView: UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        //测试开启转动 开始执行静默加载的时候转动
        return indicator
    }()
    //SinaHomeViewModel
    lazy var homeViewModel :SinaHomeViewModel = SinaHomeViewModel()
    //tipLabel
    private lazy var tipLabel: UILabel = {
        let l = UILabel(title: "", fontSize: 16, textColor: UIColor.white)
        //设置背景颜色
        l.backgroundColor = UIColor.orange
        //设置隐藏
        l.textAlignment = .center
        l.isHidden = true
        return l
    }()
    //刷新控件
    lazy var sinaRefreshControl:SinaRefreshControl = SinaRefreshControl()
    //MARK: -
    //MARK: - 设置根视图的大小
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
//        print(self.view.bounds)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置访客视图信息  -->  获取访客视图
        if !userLogin {//用户没有登录
            visitorView.updateInfo(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            return
            
            
        }

        setupTableView()
        //进入页面就开始加载数据
        //MARK: -
        //MARK: - ⭐️第1.次加载数据
        loadData()
    }
    //MARK: -
    //MARK: - 加载数据(封装homeviewmodel中加载数据的方法)
    func loadData(){
        
        homeViewModel.loadData(isPullup: indicatorView.isAnimating) { (issuccess,c) in
            
            if !issuccess{
                return
            }
            if !self.indicatorView.isAnimating{
                self.startAnimtaion(count: c)
            }
            //需要停止菊花转动,否则只能加载两次数据(初次+第二次)
            self.indicatorView.stopAnimating()
            
//            self.refreshControl?.endRefreshing()
            self.sinaRefreshControl.endRefreshing()
            self.tableView.reloadData()
        }
    
    }
    //MARK: -
    //MARK: - 设置TableView
    private func setupTableView(){
        
        //注册原创微博cell
        let originalCellNib = UINib(nibName: "SinaStatusCell", bundle: nil)
        tableView.register(originalCellNib, forCellReuseIdentifier: StatusCellId)
        //注册转发微博的cell
        let retweetedCellNib = UINib(nibName: "SinaRetweetedStatusCell", bundle: nil)
        tableView.register(retweetedCellNib, forCellReuseIdentifier: RetweetedCellId)
        //tableView.rowHeight = 350//改为自动计算行高
        //cell之间的分隔线
        tableView.separatorStyle = .none
        //设置tableFooterView
        tableView.tableFooterView = indicatorView
        //添加tipLabel
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        //self.view.addSubview(tipLabel)
        //添加导航视图控制器的根视图上
        //设置Y值
        tipLabel.frame.origin.y = navBarHeight - 35
        //self.navigationController?.view.addSubview(tipLabel)
        //移动到导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
        //添加自定义RefreshControl
//        let refreshcontrol = SinaRefreshControl()
//        self.view.addSubview(refreshcontrol)
        self.view.addSubview(sinaRefreshControl)
        //监听事件
        //MARK: -
        //MARK: - ⭐️第3.次加载数据 ‼️接收refreshcontrol中的事件
        sinaRefreshControl.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
        
    }
    //MARK: -
    //MARK: - 开始动画,并返回新微博数
    private func startAnimtaion(count: Int) {
        //如果正在做动画就直接返回
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博" : "有\(count)条微博"
        //设置文字
        tipLabel.text = tipText
        //1. 在开始动画前显示tipLabel
        self.tipLabel.isHidden = false
        
        //在开始动画之前记录Y值
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            //2. 做动画 修改Y值
            self.tipLabel.frame.origin.y = navBarHeight
            }, completion:{ (_) -> () in
                //3. 回去的动画  延迟
                UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                    self.tipLabel.frame.origin.y = y
                    }, completion: { (_) -> () in
                        self.tipLabel.isHidden = true
                })
        })
    }

    //
    //MARK: -
    //MARK: - 点击rightItem跳转
    @objc private func pushVC(){
        let demo = SinaProfileTableVC()
        demo.view.backgroundColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
        self.navigationController?.pushViewController(demo, animated: true)
        
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
}
//MARK: -
//MARK: - Delegate&DataSource
extension SinaHomeTableVC{
    //行数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.homeViewModel.viewmodelArray.count
    }
    
    //cell
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //根据viewmodel判断使用哪一个可重用标识符
        let viewmodel = self.homeViewModel.viewmodelArray[indexPath.row]
        let cellId = getCellId(viewmodel: viewmodel)
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! SinaStatusCell
        //cell.textLabel?.text = viewmodel.status?.text
        cell.viewmodel = viewmodel
        
        return cell
    }
    private func getCellId(viewmodel:SinaStatusViewModel) -> String{
        
        return viewmodel.status?.retweeted_status == nil ? StatusCellId:RetweetedCellId
        
    }
    
    //先调用获取行高的协议方法
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //获取cell
        let viewmodel = self.homeViewModel.viewmodelArray[indexPath.row]
        //let cellId = getCellId(viewmodel: viewmodel)
        //从缓存池中获取一个cell
        //cell循环引用:由于tableView要显示先调用获取行高的方法  -> 在行高的方法内部会获取缓存的cell  -> dequeueReusableCell: indexPath内部会调用 -> heightForRowAt:
        //获取cell的时候就不能够使用 dequeueReusableCell: indexPath
        //解决:使用NSBundle的方式加载cell文件']\
        let name = nibName(viewmodel: viewmodel)
        let cell = UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil).last as! SinaStatusCell
        //let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HMStatusCellpri
        //绑定数据
        
        cell.viewmodel = viewmodel
        //cell是自动布局, 设置了数据自动布局并没有立即生效
        cell.layoutIfNeeded()
//        print(cell.toolBar.frame.maxY)
        return (cell.toolBar.frame.maxY)
    }
    private func nibName(viewmodel: SinaStatusViewModel) -> String {
        return (viewmodel.status?.retweeted_status == nil) ? "SinaStatusCell" : "SinaRetweetedStatusCell"
    }
    
    //cell将要显示(如果是倒数第二个cell,并且菊花没有转动的时候,就开始执行静默加载)
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indicatorView.isAnimating == false && indexPath.row == homeViewModel.viewmodelArray.count - 2{
            
            indicatorView.startAnimating()
            //print("小菊花妈妈课堂开课啦!")
            //请求更多数据
            //MARK: -
            //MARK: - ⭐️第2.次加载数据
            loadData()
        }
    }
    
    
}







